package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/juju/ratelimit"
	"net/http"
	"time"
)

// 限流中间件
// 参考文档：https://zhuanlan.zhihu.com/p/354064637
// 参考文档：https://blog.csdn.net/weixin_44054396/article/details/120043534
func RateLimitMiddleware(fillInterval time.Duration, cap, quantum int64) gin.HandlerFunc {
	bucket := ratelimit.NewBucketWithQuantum(fillInterval, cap, quantum)
	return func(c *gin.Context) {
		if bucket.TakeAvailable(1) < 1 {
			c.String(http.StatusForbidden, "rate limit...")
			c.Abort()
			return
		}
		fmt.Println("限流中间件")
		c.Next()
	}
}
